<script lang="ts" setup>
import { onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch } from "vue"
import { deleteTableDataApi, getTableDataApi, getTableInfoApi, saveTableDataApi } from "@/api/news/news"
import { type TableData, type CreateOrUpdateTableRequestData } from "@/api/news/types/news"
import { type FormInstance, type FormRules, ElMessage, ElMessageBox, UploadProps } from "element-plus"
import { Search, Refresh, CirclePlus, RefreshRight } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"
import { cloneDeep } from "lodash-es"
import { getSelectDataApi } from "@/api/news/category"
import { SelectData, UploadUrl, WangUploadUrl } from "@/api/common/common"
import { getToken } from "@/utils/cache/cookies"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import "@wangeditor/editor/dist/css/style.css" // 引入 css

defineOptions({
  // 命名当前组件
  name: "newsIndex"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateTableRequestData = {
  id: 0,
  title: "",
  cid: 0,
  intro: "",
  image_url: "",
  published_at: "",
  detail: "",
  is_use: 20
}
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateTableRequestData>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<CreateOrUpdateTableRequestData> = {
  title: [{ required: true, trigger: "blur", message: "请输入新闻标题" }],
  cid: [{ required: true, trigger: "blur", message: "请选择新闻分类" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    saveTableDataApi(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        dialogVisible.value = false
        getTableData()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = cloneDeep(DEFAULT_FORM_DATA)
}
//#endregion

//#region 删
const handleDelete = (row: TableData) => {
  ElMessageBox.confirm(`正在删除新闻：${row.title}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteTableDataApi({ id: row.id }).then(() => {
      ElMessage.success("删除成功")
      getTableData()
    })
  })
}
//#endregion

//#region 改
const handleUpdate = (row: TableData) => {
  getTableInfoApi({ id: row.id }).then((data) => {
    formData.value = cloneDeep(data)
    dialogVisible.value = true
  })
}
//#endregion

//#region 查
const tableData = ref<TableData[]>([])
const categoryData = ref<SelectData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  keyword: "",
  phone: ""
})
const getTableData = () => {
  loading.value = true
  getTableDataApi({
    page: paginationData.currentPage
  })
    .then((data) => {
      paginationData.total = data.total
      tableData.value = data.items
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion
const token = getToken()
const headers = { authorization: token }
const handleImageSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  formData.value.image_url = URL.createObjectURL(uploadFile.raw!)
}

const beforeImageUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!")
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!")
    return false
  }
  return true
}

const editorRef = shallowRef()
const toolbarConfig = {}
const editorConfig = { placeholder: "请输入新闻详细内容..." }

editorConfig.MENU_CONF = {
  uploadImage: {
    server: WangUploadUrl,
    // form-data fieldName ，默认值 'wangeditor-uploaded-image'
    fieldName: "file",
    // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
    allowedFileTypes: ["image/*"],
    // 自定义增加 http  header
    headers: headers
  },
  uploadVideo: {
    server: WangUploadUrl,
    // form-data fieldName ，默认值 'wangeditor-uploaded-video'
    fieldName: "file",

    // 单个文件的最大体积限制，默认为 10M
    maxFileSize: 20 * 1024 * 1024, // 5M

    // 选择文件时的类型限制，默认为 ['video/*'] 。如不想限制，则设置为 []
    allowedFileTypes: ["video/*"],

    // 自定义增加 http  header
    headers: headers,

    // 超时时间，默认为 30 秒
    timeout: 10 * 60 * 1000 // 15 秒
  }
}

onMounted(() => {
  getTableData()
  getSelectDataApi().then((data) => {
    categoryData.value = data
    formData.value.cid = data[0].value
  })
})

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="keyword" label="关键字">
              <el-input v-model="searchData.keyword" placeholder="请输入" />
            </el-form-item>
            <el-form-item>
              <el-button type="danger" :icon="Search" @click="handleSearch">查询</el-button>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="CirclePlus" @click="dialogVisible = true">新增新闻</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getTableData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" border>
          <el-table-column prop="image_url" width="230" label="新闻图片" align="center">
            <template #default="scope">
              <el-image
                style="width: 200px; height: 110px; background-color: #efefef"
                :src="scope.row.image_url"
                fit="fill"
              />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="新闻信息" align="left">
            <template #default="scope">
              <div style="padding: 0 10px">
                <div class="name">{{ scope.row.title }}</div>
                <div class="category">分类：{{ scope.row.cid_name }} | 发布时间：{{ scope.row.published_at }}</div>
                <div>{{ scope.row.intro }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="is_use" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.is_use == 10" type="success" effect="plain">启用</el-tag>
              <el-tag v-else type="danger" effect="plain">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template #default="scope">
              <el-button type="primary" bg size="small" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button type="danger" bg size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formData.id === undefined ? '新增新闻' : '修改新闻'"
      @closed="resetForm"
      width="900px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="top">
        <el-row>
          <el-col :span="7">
            <el-form-item prop="image_url" label="课程图片">
              <el-upload
                class="avatar-uploader"
                :action="UploadUrl"
                :headers="headers"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                :before-upload="beforeImageUpload"
              >
                <img v-if="formData.image_url" :src="formData.image_url" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="17">
            <el-form-item prop="title" label="课程名称">
              <el-input v-model="formData.title" placeholder="请输入课程名称" />
            </el-form-item>
            <el-row>
              <el-col :span="14">
                <el-form-item prop="cid1" label="课程分类">
                  <el-select v-model="formData.cid" placeholder="选择新闻分类">
                    <el-option v-for="item in categoryData" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="9" :offset="1">
                <el-form-item prop="is_use" label="状态" required>
                  <el-select v-model="formData.is_use" placeholder="选择状态">
                    <el-option label="启用" :value="10" />
                    <el-option label="禁用" :value="20" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-form-item prop="intro" label="新闻简介">
          <el-input type="textarea" v-model="formData.intro" :rows="2" placeholder="请输入新闻简介" />
        </el-form-item>
        <el-form-item prop="intro" label="新闻详情">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 600px; overflow-y: hidden"
              v-model="formData.detail"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .avatar {
  width: 240px;
  height: 135px;
  display: block;
}

.name {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 10px;
}
.category {
  font-size: 14px;
  margin-bottom: 10px;
  line-height: 30px;
  color: #f56c6c;
  border-bottom: 1px solid #efefef;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 240px;
  height: 135px;
  text-align: center;
}
</style>
